/**
 * 场景二维码相关服务
 * weixin-qrcode-service
 * @authors 杨兴洲（of2502）
 * @date    2017/5/18 0018 17:29
 * @version 1.0
 */

import * as rp from "request-promise-native";
const HOST = 'https://api.weixin.qq.com/cgi-bin';

type ACTION_NAME = "QR_SCENE" | "QR_STR_SCENE" | "QR_LIMIT_SCENE" | "QR_LIMIT_STR_SCENE";
interface ACTION_INFO {
    scene: {
        scene_id?: number,
        scene_str?: string
    }
}

export default class WeixinQRCodeService {

    /**
     * 创建二维码ticket
     * @param access_token
     * @param action_name
     * @param action_info
     * @param expire_seconds 临时二维码需要.不传默认30. 最大值2592000（即30天)
     * @returns {Promise<any>}
     */
    static createQRCode({access_token, action_name, action_info, expire_seconds}: {
        access_token: string, action_name: ACTION_NAME, action_info: ACTION_INFO, expire_seconds?: number
    }): Promise<any> {
        return rp({
            method: 'POST',
            uri: `${HOST}/qrcode/create`,
            body: {action_name, action_info, expire_seconds},
            qs: {access_token},
            json: true
        })
            .then((data: any) => data.errcode ? Promise.reject(data) : data);

    }

    /**
     * 通过ticket换取二维码
     * @param ticket
     * @returns {Promise<any>}
     */
    static getPicture(ticket: string): Promise<any> {
        return rp({
            method: 'GET',
            uri: `https://mp.weixin.qq.com/cgi-bin/showqrcode`,
            qs: {ticket: encodeURIComponent(ticket)},
            json: true
        })
            .then((data: any) => data.errcode ? Promise.reject(data) : data);

    }
}
